﻿using System;
using System.Windows;
using Kiva7.Media;
using Kiva7.Utilities;
using Image = System.Windows.Controls.Image;

namespace Kiva7.Controls
{
    public partial class YouTubeImageControl 
    {
        public YouTubeImageControl()
        {
            InitializeComponent();

            image.ImageOpened += ImageOpened;
        }

        protected override Image Image
        {
            get { return image; }
        }



        public string Text
        {
            get { return (string) GetValue(TextProperty); }
            set
            {
                SetValue(TextProperty, value);
            }
        }

        public static readonly DependencyProperty TextProperty =
                        DependencyPropertyExt.Register<YouTubeImageControl, string>(x => x.Text, new PropertyMetadata(TextChanged));
        private static void TextChanged(DependencyObject d,
                             DependencyPropertyChangedEventArgs e)
        {
            YouTubeImageControl pc = d as YouTubeImageControl;
            if (pc != null)
            {
                pc.textBlock.Text= (string)e.NewValue;
            }

        }

        public YouTubeThumbnailSize ThumbnailSize { get; set; }

        public string YouTubeId
        {
            get { return (string)GetValue(YouTubeIdProperty); }
            set { SetValue(YouTubeIdProperty, value); }
        }

        public static readonly DependencyProperty YouTubeIdProperty =
                        DependencyPropertyExt.Register<YouTubeImageControl, string>(x => x.YouTubeId,
                                                                             new PropertyMetadata(EntityChanged));

        private static void EntityChanged(DependencyObject d,
                                     DependencyPropertyChangedEventArgs e)
        {
            YouTubeImageControl pc = d as YouTubeImageControl;
            if (pc != null)
            {
                pc.EntityChanged();
            }

        }

        public override Uri CreateImageUri()
        {
            if (!string.IsNullOrEmpty(YouTubeId))
            {
                return YouTube.GetThumbnailUri(YouTubeId, ThumbnailSize);
            }
            return null;
        }

        public override string GetImageDirectoryName()
        {
            return "YouTube" + ThumbnailSize;
        }

        public override string GetImagePath()
        {
            if (string.IsNullOrEmpty(YouTubeId))
            {
                return null;
            }
            return System.IO.Path.Combine(GetImageDirectoryName(), this.YouTubeId + ".JPG");
        }

        private void ShowVideo()
        {
            YouTube.Play(YouTubeId);
        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ShowVideo();
        }
        
    }
}
